package com.huibo.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huibo.algorithm.Store;
import com.huibo.algorithm.Stuff;
import com.huibo.algorithm.StuffOperator;
import com.huibo.common.R;
import com.huibo.common.WorkForm;
import com.huibo.entity.Company;
import com.huibo.entity.Employee;
import com.huibo.service.CompanyService;
import com.huibo.service.EmployeeService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/company")
public class CompanyController {
    @Autowired
    private CompanyService companyService;

    @Autowired
    private  EmployeeService employeeService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 店铺新增操作
     * @param company
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody Company company){
        String name = company.getName();
        LambdaQueryWrapper<Company> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotEmpty(name),Company::getName,name);
        Company one = companyService.getOne(queryWrapper);
        if(one != null){
            return R.error("店铺重名，店铺已存在");
        }else {
            companyService.save(company);
            return R.success("店铺保存成功");
        }
    }


    /**
     * 更新店铺操作
     * @param company
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody Company company){
        //先更新company
        boolean b = companyService.updateById(company);
        //店铺参数更新，与之对应的排班也要更新
        List<String> list = new ArrayList<>();
        list.add("1_"+company.getName());
        list.add("2_"+company.getName());
        list.add("3_"+company.getName());
        list.add("4_"+company.getName());

        for(int i = 0;i<list.size();i++){
            WorkForm workForm = dataPro(company.getName(), company.getId());
            String string = JSON.toJSONString(workForm);
            redisTemplate.opsForValue().set(list.get(i),string);
        }
        if(b){
            return R.success("店铺更新成功，排班表更新成功");
        }else{
            return R.error("更新失败");
        }
    }

    /**
     * 删除店铺
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(Long ids){
        LambdaQueryWrapper<Company> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Company::getId,ids);
        boolean remove = companyService.remove(queryWrapper);
        if(remove){
            return R.success("删除成功");
        }else{
            return R.error("删除失败");
        }
    }

    /**
     * 单个查询店铺
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Company> getById(@PathVariable Long id){
        Company company = companyService.getById(id);
        if(company!=null){
            return R.success(company);
        }
        return R.error("查询失败");
    }

    /**
     * 查询所有店铺
     * @return
     */
    @GetMapping("/getAll")
    public R<List<Company>> getAll(){
        List<Company> list = companyService.list();
        return R.success(list);
    }

    public  WorkForm dataPro(String marketId,Long id){
        //用来存放算法中的员工
        HashMap<String, Stuff> stuff_arr = StuffOperator.stuff_arrInit();
        //存放对应店铺的员工集
        List<Employee> employeeList = new ArrayList<>();

        //构造查询条件
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotEmpty(marketId),Employee::getMarketId,marketId);

        //查询
        employeeList = employeeService.list(queryWrapper);


        //将查询出来的员工放入到map集合中
        for(int i = 0;i<employeeList.size();i++){
            Employee employee = employeeList.get(i);
            Stuff temp = new Stuff(employee.getId(),employee.getName(), employee.getPos(), employee.getPhone(), employee.getMail(), employee.getMarketId(), employee.getLoves());
            stuff_arr.put(temp.getName(),temp);
        }

        //查询到对应店铺
        Company company = companyService.getById(id);

        //这里只是把基本的信息传给了从company传给了store,里面一些重要的参数比如preWorkTime
        Store store1 = new Store(company.getName(),company.getAddress(),company.getSize(),stuff_arr);
        //下面这段代码又臭又长，是为了当company中这些参数和store1中不一样时，做个校验
        //后面我们可以修改company的这些属性来达到实现固定和自定义规则
        store1.setPreWorkTime(company.getPreWorkTime());
        store1.setStoreSizeNeedBefore(company.getStoreSizeNeedBefore());
        store1.setPassengerFlowNeed(company.getPassengerFlowNeed());
        store1.setFree_population(company.getFreePopulation());
        store1.setAftWorkTime(company.getAftWorkTime());
        store1.setStoreSizeNeedAfter1(company.getStoreSizeNeedAfter1());
        store1.setStoreSizeNeedAfter2(company.getStoreSizeNeedAfter2());

        long[] employeeNum = new long[stuff_arr.size()]; //存放的是员工id的顺序
        List<Map<String,List<Integer>>> out = new ArrayList<>();


        for(int i = 1;i<=7;i++){
            List<List<Integer>> list = store1.decode(i,employeeNum); //存放的是每个员工一天的工作是否
            Map<String,List<Integer>> res = new HashMap<>();
            for(int j = 0;j<list.size();j++){
                //查名字
                for(Employee e : employeeList){
                    if(e.getId() == employeeNum[j]){
                        res.put(e.getName(),list.get(j));
                        break;
                    }
                }
            }
            out.add(res);
        }
        WorkForm workForm = new WorkForm(out.get(0),out.get(1),out.get(2),out.get(3),out.get(4),out.get(5),out.get(6));
        return workForm;
    }
}
